<template>
  <div style="display: flex">
    <a-upload
      name="file"
      accept="image/*"
      list-type="picture-card"
      :show-upload-list="false"
      :customRequest="uploadImageFile"
    >
      <div>
        <a-icon :type="uploadStatus ? 'loading' : 'plus'" />
        <div class="ant-upload-text">
          上传图片
        </div>
      </div>
    </a-upload>
    <div v-if="imgUrl" class="img-item">
      <img :src="imgUrl" />
    </div>
  </div>
</template>

<script>
export default {
  name: 'SingleImage',
  props: {
    url: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      imgUrl: '',
      uploadStatus: false
    }
  },
  mounted () {
    this.imgUrl = this.url
  },
  methods: {
    // 上传图片
    uploadImageFile (file) {
      console.log('file', file)
      this.uploadStatus = true // 按钮状态
      const formData = new FormData()
      formData.append('file', file.file)
      this.$common.uploadImageFile(formData).then(data => {
        console.log(data)
        if (data.code === 200) {
          const result = data.data
          this.imgUrl = result.url
          this.$emit('ok', result.url)
        } else {
          this.$message.error(data.message)
        }
      }).finally(() => {
        this.uploadStatus = false
      })
    }
  },
  watch: {
    url (val) {
      this.imgUrl = val
    }
  }
}
</script>

<style lang="less" scoped>
.img-item{
  width: 104px;
  height: 104px;
  img{
    max-height: 104px;
  }
}
/deep/ .ant-upload-picture-card-wrapper{
  width: 120px;
}
</style>
